package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * ClassName: Mytask
 * Package: com.sky.task
 * Description:
 *
 * @Author 龙培
 * @Create 2025/3/17 14:35
 * @Version 1.0
 */
@Component
@Slf4j
public class Mytask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 0/1 * * * ? ") // 每1分钟执行一次
    public void processTimeoutOrder() {
        log.info("处理超时订单");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15); //这个时间之前的未支付的订单都是超时的订单
        List<Orders> list = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,time);
        if(list.size() > 0){
            for(Orders order : list){
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单超时未支付，自动取消");
                orderMapper.update(order);
            }
        }
    }

    /**
     * 处理过期订单
     */
    @Scheduled(cron = "* * 1 * * ? ") // 每天凌晨1点执行一次
    public void processExpiredOrder() {
        log.info("处理过期订单");
        LocalDateTime time = LocalDateTime.now().plusHours(-1); // 这个时间之前的订单都是过期的
        List<Orders> list = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS,time);
        if(list.size() > 0){
            for(Orders order : list) {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            }
        }
    }
}
